package org.leetcode.middle.leetcode114;

import org.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class Solution {


    public  void flatten2(TreeNode root){
        if (root==null){
            return;
        }

        List<TreeNode> resList = getList2(root, new ArrayList<>());
        TreeNode temp = root;

        for (int i = 1; i < resList.size(); i++) {
            temp.left=null;
            temp.right= resList.get(i);
            temp=temp.right;
        }


    }

    private List<TreeNode> getList2(TreeNode root,List<TreeNode> list){
        if (root!=null){
            list.add(root);
            getList2(root.left,list);
            getList2(root.right,list);
        }
        return list;
    }



    public static void flatten(TreeNode root) {

        List<Integer> list = new ArrayList<>();

        getList(root,list);
        TreeNode current = root;
        for (int i = 1; i < list.size(); i++) { // 从索引1开始，因为索引0是根节点本身
            current.right = new TreeNode(list.get(i));
            current.left = null;
            current = current.right;
        }

//        list.remove(0);
//
//        TreeNode temp=new TreeNode(root.val);
//
//        root=temp;
//        for (int num:list) {
//            temp.right=new TreeNode(num);
//            temp.left=null;
//            temp=temp.right;
//        }
    }

    private static void getList(TreeNode root, List list){

        if (root==null){
            return;
        }

        list.add(root.val);

        getList(root.left,list);

        getList(root.right,list);

    }

    public static void main(String[] args) {
        // 先创建所有节点
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node6 = new TreeNode(6);
        TreeNode node2 = new TreeNode(2, node3, node4); // 2为根节点的左子树，3和4为子节点
        TreeNode node5 = new TreeNode(5, null, node6); // 5为根节点的右子树，左子节点为空，6为右子节点
        TreeNode root = new TreeNode(1, node2, node5); // 1为根节点，2和5为子节点

        flatten(root);
    }

}
